# -*- coding: utf-8 -*-
# @Time    : 2019/10/15 20:38
# @Author  : LiHaowen
# @Email   : lihaowen2017@163.com
# @File    : contextlib_with.py
import contextlib


@contextlib.contextmanager  # 将一个函数变成一个上下文管理器，函数必须是生成器
def file_open(file_name):
    print("file open")  # 相当于def __enter__(self):里的代码
    yield{}
    print("file end")  # 相当于def __exit__(self):里的代码


with file_open("li.txt") as f_opened:
    print("file processing")

""" 上下文实际应用场景
from contextlib import contextmanager
from time import time

@ contextmanager
def record_time():
    start = time()
    yield 'hello'
    end = time()
    print(f'执行时间;{end - start}秒')


def fac(num):
    if num in(0, 1):
        return 1
    return num * fac(num - 1)


with record_time() as msg:
    print(msg)
    print(fac(900))
"""
